package org.spring.flower.student.rule;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;

import javax.annotation.Resource;

public class NocasServiceRibbonRule extends AbstractLoadBalancerRule {

    @Resource
    private NacosDiscoveryProperties discoveryProperties;
    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object key) {
        try {
            // 获取
            BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
            // 获取请求服务器的名词
            String name = loadBalancer.getName();
            // 实现负载均衡算法
            NamingService namingService = discoveryProperties.namingServiceInstance();
            // nacos client自动通过基于权重的负载均衡算法，获取一个服务实例
            Instance instance = namingService.selectOneHealthyInstance(name);
            System.out.println("服务的实例是：" + instance.getPort());
            // 返回一个服务实例
            return new NacosServer(instance);
        } catch (NacosException e) {
            e.printStackTrace();
            return null;
        }
    }
}
